package com.jang.client;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * title UploadTester
 * projectName springcloud
 * desc 文件上传测试
 *
 * @author jiangjian
 * @date 2020/8/14 15:58
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class UploadTester {

    @Autowired
    private UploadService uploadService;

    @Test
    @SneakyThrows
    public void testHandleFileUpload() {
        File file = new File("D:\\Projects\\Java\\springcloud\\eureka-feign-upload-client\\src\\main\\resources\\static\\upload.txt");
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.TEXT_PLAIN_VALUE, true, file.getName());

        InputStream in = new FileInputStream(file);
        OutputStream out = fileItem.getOutputStream();
        IOUtils.copy(in, out);

        CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);

        String fileName = uploadService.handleFileUpload(multipartFile);
        log.info(fileName);
        Assert.assertEquals("文件名", "upload.txt", fileName);
    }
}
